package com.bdc.whatwhat.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.Uri;
import android.view.View;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by dev-w8-gfi on 05/08/2014.
 */
public class ImageUtils {

    public static Bitmap getBitmapFromView(View view) {
        //Define a bitmap with the same size as the view
        Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
        //Bind a canvas to it
        Canvas canvas = new Canvas(returnedBitmap);
        //Get the view's background

        // draw the view on the canvas
        view.draw(canvas);
        //return the bitmap
        return returnedBitmap;
    }

    public static void sendImageShare(Context context,View view){
        try {
            File cache = context.getExternalCacheDir();
            File sharefile = new File(cache,"toshare.png");

            try {
                Bitmap bitmap = getBitmapFromView(view);
                FileOutputStream out = new FileOutputStream(sharefile);
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }


            // Now send it out to share
            Intent share = new Intent(android.content.Intent.ACTION_SEND);
            share.setType("image/*");
            share.putExtra(Intent.EXTRA_STREAM,
                    Uri.parse("file://" + sharefile));

            context.startActivity(Intent.createChooser(share,
                    "Share Image"));

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
